package com.powernode.springboot.component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import com.powernode.springboot.bean.User;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 消息转换器。专门处理yaml格式的
 * 必须要实现HttpMessageConverter接口，或者继承AbstractHttpMessageConverter抽象类，并实现方法
 */
public class YamlHttpMessageConverter extends AbstractHttpMessageConverter<Object> {
    private ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory().disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER));

    public YamlHttpMessageConverter() {
        //媒体类型。与配置的value要对应上"text/yaml"
        super(new MediaType("text", "yaml", StandardCharsets.UTF_8));
    }

    //此方法用于指定，哪些类型的对象可以使用该类型的转换成
    @Override
    protected boolean supports(Class<?> clazz) {
        //表示只有User类型的对象才能够使用该消息转传奇进行转换
        return User.class.isAssignableFrom(clazz);
    }

    //将yaml格式的字符串转换成java对象
    @Override
    protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }

    //将java对象转换成yaml格式的字符串
    @Override
    protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        //把输出流写成对象
        this.objectMapper.writeValue(outputMessage.getBody(), o);
    }
}
